<?php

namespace app\api\controller;

use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomBoardModel;
use app\admin\model\BuildingRoomFixedModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\BuildingRoomPtModel;
use app\admin\model\BuildingZoneModel;
use app\admin\model\CostConfigModel;
use app\admin\model\HouseModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;


class Room extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @var BuildingRoomModel
     */
    protected $model = null;

    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new BuildingRoomModel();
        $this->user_id = $this->auth->id;
    }

    public function index()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $kw = $this->request->param('kw/s', '');
        $where = [];
        if ($kw) {
            $where['name|remark'] = ['like', '%' . $kw . '%'];
        }
        $where['user_id'] = $this->user_id;
        $list = $this->model
            ->where($where)
            ->order('id', 'desc')
            ->paginate($page_size);

        $this->success('请求成功', $list);
    }


    public function room_type_list()
    {
        $this->success('ok', $this->model->getTypeList());
    }

    public function info()
    {
        $id = $this->request->param('id/', 0);
        if ($id < 1) {
            $this->error('id错误');
        }
        $room = BuildingRoomModel::get($id, ['board' => function ($query) {
            $query->field('create_time,update_time,delete_time', true);
        }, 'fixed' => function ($query) {
            $query->field('create_time,update_time,delete_time', true);
        }, 'pt' => function ($query) {
            $query->field('create_time,update_time,delete_time', true);
        }, 'building' => function ($query) {
            $query->field('id,name,address');
        }]);
        if (empty($room)) {
            $this->error('房间不存在');
        }
        if (!empty($room->building)) {
            $room->building->append([],true);
        }

        unset($room['delete_time'], $room['del_uid']);

        $house = HouseModel::where([
            'room_id' => $id,
        ])->order('id','desc')->find();
        $room->house = $house;
        $room['house_id'] = $house['id'] ?? 0;
        $room['contract_id'] = \app\common\model\Contract::where([
            'room_id' => $id,
            'status' => ['in' , [0,1]],
        ])->order('id', 'desc')->value('id');


        $this->success('ok', $room);
    }

    public function add()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->param();
        $checkRes = $this->validate($params, [
            'zone_id|楼栋区域' => 'require',
            'build_id|楼栋id' => 'require',
            'type|房屋类型' => 'require|integer',
            'floor_no|楼层号' => 'integer',
            'name|房间号' => 'require',
            'price|租金' => 'require|number',
            'area|面积' => 'require|number',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        $build = BuildingModel::where('id', $params['build_id'])
            ->where("find_in_set($this->user_id,user_id)")
            ->find();
        if (empty($build)) {
            $this->error('楼栋ID不存在');
        }

        $exist = $this->model->where([
            'build_id' => $params['build_id'],
            'name' => $params['name'],
        ])->count();
        if ($exist) {
            $this->error('房间号已存在');
        }


        unset($params['id'], $params['create_time'], $params['update_time'], $params['delete_time'], $params['del_uid']);
        unset($params['house_id']);
        Db::startTrans();
        try {
            $params['user_id'] = $this->user_id;
            $params['floor'] = $params['floor_no'];
            $create = BuildingRoomModel::create($params ,true);
            if (empty($create->id)) {
                throw new Exception('创建房间失败');
            }
            $room_id = $create->id;

            if (!empty($params['fixed'])) {
                $fixed_data = [];
                $board_data = [];
                foreach ($params['fixed'] as $item) {
                    $fixed_data[] = [
                        'room_id' => $room_id,
                        'cfg_id' => $item['id'],
                        'type_name' => $item['name'],
                        'price' => $item['price'],
                    ];

                    if (in_array($item['id'], [1, 2, 3])) {
                        $board_data[] = [
                            'room_id' => $room_id,
                            'type' => $item['id'],
                            'name' => $item['name'],
                            'price' => $item['price'],
                        ];
                    }

                }
                (new BuildingRoomFixedModel())->allowField(true)->saveAll($fixed_data);

                if ($board_data) {
                    (new BuildingRoomBoardModel())->allowField(true)->saveAll($board_data);
                }
            }

            // 配套处理
            $facilities = [];
            if (!empty($params['pt'])) {

                $pt_data = [];
                foreach ($params['pt'] as $item) {
                    $pt_data[] = [
                        'room_id' => $room_id,
                        'option_id' => $item['id'],
                        'name' => $item['name'],
                    ];
                    $facilities[] = $item['id'];
                }
                (new BuildingRoomPtModel())->allowField(true)->saveAll($pt_data);
            }


            // 同步添加房源
            $house = new HouseModel();
            $params['room_id'] = $room_id;
            $params['user_id'] = $this->user_id;
            $params['rent'] = $params['price'] ?? $params['rent'];
            $params['name'] = $params['title'];
            $params['status'] = 1;
            $params['facilities'] = implode(',', $facilities);
            $params['region'] = BuildingZoneModel::where('id', $params['zone_id'])->value('name', '');
            if (empty($params['community'])) {
                $params['community'] = $this->cun_id;
            }
            if ($params['type'] == 1 && empty($params['house_type'])) {
                $params['house_type'] = sprintf('%d室%d厅%d卫', $params['room_num'] ?? 0, $params['ting_num'] ?? 0, $params['toilet_num'] ?? 0);
            }

            $house->allowField(true)->save($params);
            // 更新水电费用
            BuildingRoomModel::syncHouseData($room_id, $house);
            $in_record['countent'] = "创建房源".$house->id;
            $in_record['ord_id'] = $house->id;
            $in_record['type'] = 0;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('添加房间异常：' . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }

        $this->success('保存成功');
    }


    public function cost_list()
    {
        $data = CostConfigModel::field('id,name,icon,unit')->select();
        $this->success('成功', $data);
    }


    public function edit()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'zone_id|楼栋区域' => 'require',
            'room_id|房间id' => 'require',
            'build_id|楼栋id' => 'require',
            'type|房屋类型' => 'require|integer',
            'floor_no|楼层号' => 'integer',
            'name|房间号' => 'require',
            'price|租金' => 'require|number',
            'area|面积' => 'require|number',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        $build = BuildingModel::where('id', $params['build_id'])
            ->where("find_in_set($this->user_id,user_id)")
            ->find();
        if (empty($build)) {
            $this->error('楼栋ID不存在');
        }
        unset($params['create_time'], $params['update_time'], $params['delete_time'], $params['del_uid']);
        $room = BuildingRoomModel::get($params['room_id']);
        $room_data = BuildingRoomModel::get($params['room_id']);
        if (empty($room)) {
            $this->error('房间不存在');
        }
        Db::startTrans();
        try {

            $room->isUpdate()->allowField(true)->save($params);
            $room_id = $room->id;

            // 费用处理
            BuildingRoomBoardModel::destroy(['room_id' => $room_id], true);
            BuildingRoomFixedModel::destroy(['room_id' => $room_id], true);

            if (!empty($params['fixed'])) {
                $fixed_data = [];
                $board_data = [];
                foreach ($params['fixed'] as $item) {
                    $fixed_data[] = [
                        'room_id' => $room_id,
                        'cfg_id' => $item['id'],
                        'type_name' => $item['name'],
                        'price' => $item['price'],
                    ];

                    if (in_array($item['id'], [1, 2, 3])) {
                        $board_data[] = [
                            'room_id' => $room_id,
                            'type' => $item['id'],
                            'name' => $item['name'],
                            'price' => $item['price'],
                        ];
                    }

                }
                (new BuildingRoomFixedModel())->allowField(true)->saveAll($fixed_data);

                if ($board_data) {
                    (new BuildingRoomBoardModel())->allowField(true)->saveAll($board_data);
                }
            }

            // 配套处理
            BuildingRoomPtModel::destroy(['room_id' => $room_id], true);
            $facilities = [];
            if (!empty($params['pt'])) {

                $pt_data = [];
                foreach ($params['pt'] as $item) {
                    $pt_data[] = [
                        'room_id' => $room_id,
                        'option_id' => $item['id'],
                        'name' => $item['name'],
                    ];
                    $facilities[] = $item['id'];
                }
                (new BuildingRoomPtModel())->allowField(true)->saveAll($pt_data);
            }


            // 更新房源
            $house = HouseModel::where('room_id', $room_id)->order('id', 'desc')->find();
            if (empty($house)) {
                $house = new HouseModel();
            }
            $countent = '';

            file_put_contents('fy.txt',json_encode($params,true));
            if(isset($params['title'])) {
                if ($house->name != $params['title']) {
                    $countent .= "|原名称：" . $house->name;
                }
            }
            if(isset($params['name'])) {
                if ($room_data['name'] != $params['name']) {
                    $countent .= "|原房号：" . $room_data['name'];
                }
            }
            if(isset($params['room_num'])) {
                if ($room_data['room_num'] != $params['room_num']) {
                    $countent .= "|原房间数：" . $room_data['room_num'];
                }
            }
            if(isset($params['ting_num'])) {
                if ($room_data['ting_num'] != $params['ting_num']) {
                    $countent .= "|原客厅数：" . $room_data['ting_num'];
                }
            }
            if(isset($params['toilet_num'])) {
                if ($room_data['toilet_num'] != $params['toilet_num']) {
                    $countent .= "|原卫生间数：" . $room_data['toilet_num'];
                }
            }
            if(isset($params['price'])) {
                if ($house->rent != $params['price']) {
                    $countent .= "|原押金：" . $house->rent;
                }
            }
            if(isset($params['area'])){
                if($house->area != $params['area']){
                    $countent .= "|原面积：".$house->area;
                }
            }
            if(isset($params['house_type'])) {
                if ($room_data['house_type'] != $params['house_type']) {
                    $countent .= "|原户型：" . $room_data['house_type'];
                }
            }
            if(isset($params['floor_no'])) {
                if ($room_data['floor_no'] != $params['floor_no']) {
                    $countent .= "|原楼层：" . $room_data['floor_no'];
                }
            }
            if(isset($params['payment_type'])) {
                if ($house->payment_type != $params['payment_type']) {
                    $countent .= "|原付款方式：" . $house->payment_type;
                }
            }
            if(isset($params['type'])) {
                if ($house->type != $params['type']) {
                    $type_name = '';
                    if($house->type == 1){
                        $type_name = '居住';
                    }elseif ($house->type == 2){
                        $type_name = '商铺';
                    }elseif ($house->type == 3){
                        $type_name = '厂房';
                    }elseif ($house->type == 4){
                        $type_name = '办公';
                    }elseif ($house->type == 5){
                        $type_name = '仓库';
                    }elseif ($house->type == 6){
                        $type_name = '建材';
                    }elseif ($house->type == 7){
                        $type_name = '物业';
                    }elseif ($house->type == 8){
                        $type_name = '车位';
                    }
                    $countent .= "|原出租类型：" . $type_name;
                }
            }
//            if($house->payment_type != $params['payment_type']){
//                $countent .= "|原付款方式：".$house->payment_type;
//            }
           /* if($house->face != $params['face']){
                $countent .= "|原朝向：".$house->face;
            }
            if($house->face != $params['face']){
                $countent .= "|原朝向：".$house->face;
            }*/
            if(isset($params['deposit'])) {
                if ($house->deposit != $params['deposit']) {
                    $countent .= "|原押金：" . $house->deposit;
                }
            }
            if(isset($params['water_rate'])) {
                if ($house->water_rate != $params['water_rate']) {
                    $countent .= "|原水费：" . $house->water_rate;
                }
            }
            if(isset($params['power_rate'])) {
                if ($house->power_rate != $params['power_rate']) {
                    $countent .= "|原电费：" . $house->power_rate;
                }
            }
           /* if($house->room_num != $params['room_num']){
                $countent .= "|原房间数：".$house->room_num;
            }*/
           /* if($house->manage_rate != $params['manage_rate']){
                $countent .= "|原管理费：".$house->manage_rate;
            }*/
            if(isset($params['address'])) {
                if ($house->address != $params['address']) {
                    $countent .= "|原位置：" . $house->address;
                }
            }
            if(isset($params['zone_id'])) {
                $region = BuildingZoneModel::where('id', $params['zone_id'])->value('name', '');
                if ($house->region != $region) {
                    $countent .= "|原区域：" . $house->region;
                }
            }
            if(isset($params['notice'])) {
                if ($house->notice != $params['notice']) {
                    $countent .= "|原入住须知：" . $house->notice;
                }
            }
            /*if($house->is_ax != $params['is_ax']){
                $countent .= "|原安心房源：".$house->is_ax=1?"是":"否";
            }*/
           /* if($house->is_recommend != $params['is_recommend']){
                $countent .= "|原推荐房源：".$house->is_recommend=1?"是":"否";
            }*/
            if(isset($params['mobile'])) {
                if ($house->mobile != $params['mobile']) {
                    $countent .= "|原手机号：" . $house->mobile;
                }
            }
            if(isset($params['tags'])) {
                if ($house->tags != $params['tags']) {
                    $tags_name_str = '';
                    $tags_name = Db::name("config_value")->where(['cid'=>8,'option_id'=>['in',$house->tags]])->select();
                    foreach ($tags_name as $k=>$v){
                        $tags_name_str .= $v['option_name'].',';
                    }
                    $countent .= "|原标签：" . trim($tags_name_str,',');
                }
            }
            if(isset($params['pt'])) {
                $ids = '';

                foreach ($params['pt'] as $k=>$v){
                    $ids .= $v['id'].',';

                }
                if ($house->facilities != trim($ids,',')) {
                    $name_str = '';
                    $tags_name = Db::name("config_value")->where(['cid'=>4,'option_id'=>['in',$house->facilities]])->select();
                    foreach ($tags_name as $k=>$v){
                        $name_str .= $v['option_name'].',';
                    }
                    $countent .= "|原房间设备：" . trim($name_str,',');
                }
            }
            if(isset($house->fixed)){
                foreach ($house->fixed as $k=>$v){
                    if($v['type_name'] == '水费'){
                        if ($house->water_rate != $v['price']) {
                            $countent .= "|原水费：" . $house->water_rate;
                        }
                    }
                    if($v['type_name'] == '电费'){
                        if ($house->power_rate != $v['price']) {
                            $countent .= "|原电费：" . $house->power_rate;
                        }
                    }
                }
            }

            $in_record['countent'] = "修改房源".trim($countent,'|');
            $in_record['ord_id'] = $room_id;
            $in_record['type'] = 0;
            $in_record['createtime'] = time();
            file_put_contents('rtr2.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);

            $params['user_id'] = $this->user_id;
            $params['name'] = $params['title'];
            $params['rent'] = $params['price'] ?? $params['rent'];
            $params['status'] = 1;
            $params['facilities'] = implode(',', $facilities);
            $params['region'] = BuildingZoneModel::where('id', $params['zone_id'])->value('name', '');
            if (empty($params['community'])) {
                $params['community'] = $this->cun_id;
            }

            if ($params['type'] == 1 && empty($params['house_type'])) {
                $params['house_type'] = sprintf('%d室%d厅%d卫', $params['room_num'] ?? 0, $params['ting_num'] ?? 0, $params['toilet_num'] ?? 0);
            }

            $house->allowField(true)->save($params);
            // 更新水电费用
            BuildingRoomModel::syncHouseData($room_id, $house);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('编辑房间异常：' . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }

        $this->success('保存成功');
    }

    public function del()
    {
        $id = $this->request->param('id/d');
        $row = $this->model::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $row->data('del_uid', $this->auth->id);
        $res = $row->delete();
        if ($res) {
            HouseModel::update(['status' => 2], ['room_id' => $id]);
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    public function board_del()
    {
        $id = $this->request->param('id/d');
        $row = BuildingRoomBoardModel::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $res = $row->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function fixed_del()
    {
        $id = $this->request->param('id/d');
        $row = BuildingRoomFixedModel::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $res = $row->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function pt_del()
    {
        $id = $this->request->param('id/d');
        $row = BuildingRoomPtModel::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $res = $row->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function common_pt()
    {
        $building_ids = BuildingModel::getUserBuildingIds($this->user_id);
        $room_ids = BuildingRoomModel::whereIn('build_id', $building_ids)->column('id');
        $list = BuildingRoomPtModel::group('name')
            ->whereIn('room_id', $room_ids)
            ->field('name,num,deposit')
            ->select();

        $this->success('ok', $list);
    }



    /**
     * 发布房源
     * @return void
     */
    public function publish()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->except('id,create_time,update_time');
        if (empty($params['community'])) {
            $params['community'] = $this->cun_id;
        }


        $checkRes = $this->validate($params, [
            'room_id|房屋id' => 'require|integer',
            'type|房屋类型' => 'require|integer',
            //'name|名称' => 'require',
            //'community|社区' => 'require|integer',
            //'street|街道' => 'require|integer',
            //'facilities|房屋设施' => 'require',
            'address|楼栋地址' => 'require',
            'region|片区' => 'require',
            'floor|楼层' => 'require|integer',
            'area|面积' => 'require|number',
            'images|图片' => 'length:0,6',
        ], [
            'images.length' => '图片最多上传6张'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $user_id = $this->auth->id;
        $params['user_id'] = $user_id;

        $publish_type = \app\common\model\User::isCanPublish($user_id);
        if ($publish_type == 0) {
            $this->error('次数已用完，积分不足');
        }

        if (empty($params['name']) && !empty($params['title'])) {
            $params['name'] = $params['title'];
        }

        Db::startTrans();
        try {
            $room_info = (new BuildingRoomModel())->get(['id' => $params['room_id']]);
            if (!$room_info) {
                throw new Exception('房间不存在');
            }
            if ($room_info->status == 3) {
                throw new Exception('房间已签约');
            }
            $count = HouseModel::where('room_id', $params['room_id'])
                ->where('is_finish', 0)
                ->count();
            if ($count > 0) {
                throw new Exception('房源已经发布过了');
            }
            /*$is_audit = \app\common\model\User::where('id', $user_id)->value('is_audit');
            if ($is_audit == 0) {
                $params['status'] = 1;
            }*/
            $params['status'] = 1;
            $house = HouseModel::create($params, true);
            $in_record['countent'] = "创建房源".$house->id;
            $in_record['ord_id'] = $house->id;
            $in_record['type'] = 0;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);
            $room_info->save(['status' => 1]);
            \app\common\model\User::decPublishNum($user_id, $publish_type);
            // 更新水电费用
            BuildingRoomModel::syncHouseData($params['room_id']);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('发布房源失败：'.$e->getMessage().$e->getTraceAsString());
            $this->error($e->getMessage());
        }

        $this->success('发布成功');
    }

    public function changeLog()
    {

        $id = $this->request->post("id");
        //$id = 21;
        $type = $this->request->post("type",1);
       $list =  Db::name("record")->where(['ord_id'=>$id,'type'=>$type])->order('id desc')->paginate(15)->each(function ($item) {
           $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
           return $item;
       });
        $this->success('成功', $list);
    }
    public function changehostLog()
    {

        $id = $this->request->post("id");
        $type = $this->request->post("type",0);
        $list =  Db::name("record")->where(['ord_id'=>$id,'type'=>$type])->order('id desc')->paginate(15)->each(function ($item) {
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            return $item;
        });
       /* foreach ($list as $k=>$v){
            $list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }*/
        $this->success('成功', $list);
    }

}
